package mcu.market.net;

import java.io.IOException;
import java.util.ArrayList;

import mcu.market.ibatis.IBatisFactory;
import mcu.market.ibatis.bean.BeanCompany;

import org.apache.ibatis.session.SqlSession;

public class DBDosComand {
	String DBBinPath="D:\\PostgreSQL\\9.3\\bin\\psql.exe";
	String SaveFile="D:\\loaderOTC";
	public String getDBBinPath() {
		return DBBinPath;
	}
	public void setDBBinPath(String dBBinPath) {
		DBBinPath = dBBinPath;
	}
	public String getSaveFile() {
		return SaveFile;
	}
	public void setSaveFile(String saveFile) {
		SaveFile = saveFile;
	}
	public boolean exec(ArrayList<String> cmds) { 
		try {
	    	Process proc = null;
	    	Runtime rt = Runtime.getRuntime();
			String osName = System.getProperty("os.name" );
			for (int i=0;i<cmds.size();i++){
				/*
				 * cmd /c dir 是执行完dir命令后关闭命令窗口。 
				 * cmd /k dir 是执行完dir命令后不关闭命令窗口。 
				 * cmd /c start dir 会打开一个新窗口后执行dir指令，原窗口会关闭。 
				 * cmd /k start dir 会打开一个新窗口后执行dir指令，原窗口不会关闭。 
				 */
				String[] cmd = {"cmd.exe","/c",cmds.get(i) } ;
				if (osName.equals( "Windows 95" ))
					cmd[0] = "command.exe";
				try{
					
					System.out.println("Execute " + cmd[0] + " " +cmds.get(i));
					proc = rt.exec(cmd);
					proc.waitFor();
					int exitVal = proc.waitFor();
					System.out.println("  >> ExitValue: " + exitVal);
					
				} catch (IOException e) {
					e.printStackTrace();
		    	}
			}
			rt.exit(0);
			proc.destroy();
			return true;
		} catch (Throwable t) {
			t.printStackTrace(); 
			return false;
			} 
		}
	public ArrayList DBToCSVCmds() {
		SqlSession sqlSession=IBatisFactory.getInstance().getSqlSession();
		ArrayList<String> list = new ArrayList<String>();
		BeanCompany bean=new BeanCompany();
		bean.setType(1);
		ArrayList<BeanCompany> list_bean=(ArrayList<BeanCompany>) sqlSession.selectList("company.selectTypeCompany",bean);
		list.add("MD "+SaveFile);
		list.add(DBBinPath+" -d daily -U postgres -v client_encoding=UTF8 -c \"\\COPY (select * from company where type=0 order by sid asc) to "+SaveFile+"\\company.csv CSV HEADER\"");
		for(BeanCompany bc:list_bean){
			list.add(DBBinPath+" -d daily -U postgres -v client_encoding=UTF8 -c \"\\COPY (select * from price.\\\""+bc.getSid()+"\\\" order by day desc) to "+SaveFile+"\\"+bc.getSid()+".csv CSV HEADER\"");
		}
		return list;
	}
}
